package com.suxin.websocket.pusher;

import com.alibaba.fastjson.JSON;
import com.suxin.websocket.model.BaseModel;
import com.suxin.websocket.session.SessionHolder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Tang
 * @classname AbstractPusher
 * @description [  ]
 * @date 2022/3/24 17:32
 */
@Data
@Slf4j
public abstract class AbstractPusher<T extends BaseModel> implements Pusher<T> {

    private SessionHolder sessionHolder;

    public AbstractPusher() {

    }

    @Override
    public void push(T t) {
        if (Objects.isNull(t)) {
            return;
        }
        Session session = this.getSessionHolder().getSession(t.getKey());
        String jsonString = JSON.toJSONString(t);
        if (Objects.nonNull(session)) {
            try {
                log.info("AbstractPusher-数据推送:{}", jsonString);
                session.getBasicRemote().sendText(jsonString);
            } catch (IOException e) {
                log.error("AbstractPusher-数据推送异常:{}", jsonString);
            }
            return;
        }
        log.warn("AbstractPusher-这是一条离线消息:{}", jsonString);
    }

//    /**
//     * send client
//     * @param jsonString
//     */
//    private void send(String jsonString) {
//        Session session = this.getSessionHolder().getSession(null);
//        if (Objects.nonNull(session)) {
//            try {
//                log.error("AbstractPusher-数据推送:{}",jsonString);
//                session.getBasicRemote().sendText(jsonString);
//            } catch (IOException e) {
//                log.error("AbstractPusher-数据推送异常:{}",jsonString);
//            }
//            return;
//        }
//        log.warn("AbstractPusher-这是一条离线消息:{}",jsonString);
//    }

}